<?php

class SettingAction extends AdministratorAction {
	
	private $allowKeys = null;
	private $allowTypes = null;
	public function _initialize(){
		parent::_initialize();
		$this->configModel = D('Config');
		$this->allowKeys = array('sitename','logo','tel','email','banner','scope','contactus','aboutus');
		$this->allowTypes  = array('base', 'banner', 'aboutus', 'scope', 'contactus');
	}
	
	public function index(){
		$type = $this->_get('type');
		$type = empty($type) || !in_array($type, $this->allowTypes)? $type = 'base' : $type;
		$configData = $this->getConfigs();
		$banners = explode(',', $configData['banner']['value']);
		$this->assign('banners',$banners);
		$this->assign('configData',$configData);
		$this->display($type);
	}
	
	public function saveConfig(){
		if ( $this->isPost() ){
			foreach ( $_POST as $key=>$value ){
				if ( in_array($key, $this->allowKeys) ){
					$this->setConfig($key, $value);
				}
			}
			$this->success('保存成功');
		}
	}

	public function setConfig($key,$value){
		$where = array('key'=>$key);
		$configData = array(
				'key'=>$key,
				'value'=>$value
				);
		if ( $this->configModel->where($where)->find() && !empty($value) ){
			$status = $this->configModel->where($where)->setField('value',$value);
		}
		else{
			$status = $this->configModel->add($configData);
		}
		return $status;
	}
	
	/**
	 * 获取所有网站配置
	 */
	public function getConfigs(){
		$configs =  $this->configModel->select();
		$configData = array();
		foreach( $configs as $key=>$config ){
			$configData[$config['key']] = $config; 
		}
		return $configData;
	}
	
	/**
	 * 获取单项配置
	 * @param string $key
	 */
	public function getConfig($key){
		if ( empty($key) ){
			return false;
		}
		$where = array('key'=>$key);
		return $this->configModel->where($where)->find();
	}
	
	/**
	 * 检查表单
	 * @see AdministratorAction::_checkFormData()
	 */
	protected  function _checkFormData(){
	
	}
}